import { api, postApi } from '@/api';
import apiConfig from '@/api/config';
import DivideLine from '@/components/Divider';
import PageTitle from '@/components/PageTitle';
import TButton from '@/components/TButton';
import { API_RESULT, DEFAULT_SETTINGS } from '@/const';
import { download, toTxt, upload } from '@/utils';
import { Form, Input, message } from 'antd';
import { useEffect, useState } from 'react';
import './index.less';

interface IProps {
  settings: Record<string, string>;
  onSubmit: (newSettings: Record<string, any>) => void;
}

export default function Settings(props: IProps) {
  const { settings, onSubmit } = props;

  const [serverInfo, setServerInfo] = useState<
    { name: string; address: string }[]
  >([]);

  useEffect(() => {
    api(apiConfig.share.url).then((res) => {
      if (res.code === API_RESULT.SUCCESS) {
        setServerInfo(res.data);
      }
    });
  }, []);

  const onFinish = (values: any) => {
    onSubmit(values);
  };

  const handleReset = () => {
    onSubmit(DEFAULT_SETTINGS);
  };

  const handleClearCache = () => {
    localStorage.removeItem('todo-check-restore');
    localStorage.removeItem('todo-memo-restore');
    localStorage.removeItem('todo-plan-restore');
    window.location.reload();
  };

  const handleExport = () => {
    api(apiConfig.export.url).then((res) => {
      if (res.code === API_RESULT.SUCCESS) {
        const file = toTxt(JSON.stringify(res.data), {
          name: '工作台数据备份',
          suffix: 'json',
        });
        download(file, '工作台数据备份.json');
      }
    });
  };

  const handleImport = () => {
    upload({
      typeRule: ['json'],
      onLoad: (data: string) => {
        const source = JSON.parse(data);
        console.log(JSON.parse(data));
        postApi(apiConfig.import.url, source).then((res) => {
          if (res.code === API_RESULT.SUCCESS) {
            message.success('导入成功，将刷新');
            setTimeout(() => {
              window.location.reload();
            }, 3000);
          } else {
            message.warn(res.msg);
          }
        });
      },
      onError: (e: string) => {
        message.error(e);
      },
    });
  };

  const renderInfo = () => {
    return (
      <div className="info__container base-padding">
        {serverInfo.map((i) => (
          <div className="info__item" key={i.name}>
            <div className="info__name">{i.name}</div>
            <div className="info__value">{i.address}</div>
          </div>
        ))}
      </div>
    );
  };

  const renderSettingsForm = () => {
    const config = [
      // {
      //   field: 'mainColor',
      //   label: '主题色',
      //   component: () => (
      //     <Input placeholder="输入十六进制颜色" type="color" size="small" />
      //   ),
      // },
      // {
      //   field: 'mainActiveColor',
      //   label: '主题色（激活状态）',
      //   component: () => (
      //     <Input placeholder="输入十六进制颜色" type="color" size="small" />
      //   ),
      // },
      {
        field: 'radius',
        label: '圆角',
        component: () => (
          <Input placeholder="输入如6px格式的样式值" size="small" />
        ),
      },
    ];

    return (
      <div className="base-padding">
        <Form
          name="basic"
          initialValues={settings}
          onFinish={onFinish}
          autoComplete="off"
        >
          {config.map((i) => (
            <Form.Item label={i.label} name={i.field} key={i.field}>
              {i.component()}
            </Form.Item>
          ))}
          <Form.Item>
            <TButton
              submit
              fullWidth
            >
              确认修改
            </TButton>
          </Form.Item>
        </Form>
      </div>
    );
  };

  const renderDataBlock = () => {
    return (
      <div className="info__container base-padding">
        <div className="info__item">
          <div className="info__name">数据导出</div>
          <div className="info__value">
            <TButton onClick={handleExport}>导出</TButton>
          </div>
        </div>
        <div className="info__item">
          <div className="info__name">数据导入</div>
          <div className="info__value">
            <TButton onClick={handleImport}>导入</TButton>
          </div>
        </div>
        <div className="info__item">
          <div className="info__name">刷新缓存</div>
          <div className="info__value">
            <TButton onClick={handleClearCache}>刷新</TButton>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="settings-container">
      <PageTitle
        title="数据文件"
        subTitle={<span>数据文件的备份与导入</span>}
      />
      {renderDataBlock()}

      <PageTitle title="网络信息" subTitle={<span>局域网信息</span>} />
      {renderInfo()}
      <DivideLine top={10} />

      <PageTitle
        title="自定义项"
        subTitle={<span>个性化项目配置</span>}
        rightTitle={
          <a style={{ fontSize: '10px', color: '#999' }} onClick={handleReset}>
            重设为默认值
          </a>
        }
      />
      {renderSettingsForm()}
    </div>
  );
}
